package com.soviet.boot.common.exception;

import com.soviet.boot.common.base.ResultModel;
import com.soviet.boot.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author Dave
 * @Date 2021/7/19
 * @Description 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public Object exceptionHandler(Exception e) {
        String msg = "";
        if (!(e instanceof ServiceException)) {
            log.error(e.getMessage());
        }
        if (e instanceof ServiceException) {
            msg = e.getMessage();
        } else {
            e.printStackTrace();
            msg = ResultModel.ResultCode.ERROR.getDesc();
        }
        return new ResultModel<>(ResultModel.ResultCode.ERROR, null, msg);
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(AccessDeniedException.class)
    public Object handleAccessRE(AccessDeniedException ex) {
        return new ResultModel<>(ResultModel.ResultCode.ACCESS_DENIED, "", ResultModel.ResultCode.ACCESS_DENIED.getDesc());
    }
}
